package com.gientecher.rocketmqdemo.controller;

import com.alibaba.fastjson.JSON;
import com.gientecher.rocketmqdemo.entity.UserInfo;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

//rocketmq作业
// 1. 通过provider 和 consumer 两个spring boot 项目， 基于rocketmq, 实现简单的消息发布和订阅功能

@RestController
public class ProviderController {

    @GetMapping("/sendMessage")
    public String sendMessage() throws Exception{
        // 实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("provider");
        // 设置NameServer的地址
        producer.setNamesrvAddr("192.168.139.131:9876");
        //启动Producer实例
        producer.start();

        Message msg = new Message("TopicTest" , "TagA" , ("Hello RocketMQ").getBytes(StandardCharsets.UTF_8));
        //发送消息到一个Broker
        SendResult sentResult = producer.send(msg);
        //通过sentResult返回消息是否成功发送
        System.out.printf("%s%n", sentResult);
        //如果不再发送消息，关闭Producer实例

        producer.shutdown();
        return "发送成功";
    }

    @GetMapping("/sendUserInfo")
    public String sendUserInfo() throws Exception{
        // 实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("provider");
        // 设置NameServer的地址
        producer.setNamesrvAddr("192.168.139.131:9876");
        //启动Producer实例
        producer.start();

        UserInfo userInfo = new UserInfo("张三",30);

        Message msg = new Message("UserInfo" , "TagA" , JSON.toJSONString(userInfo).getBytes(StandardCharsets.UTF_8));
        //发送消息到一个Broker
        SendResult sentResult = producer.send(msg);
        //通过sentResult返回消息是否成功发送
        System.out.printf("%s%n", sentResult);
        //如果不再发送消息，关闭Producer实例

        producer.shutdown();
        return "发送成功";
    }
}